﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Workflow.ComponentModel;
using Microsoft.Crm.Workflow;
using System.Workflow.ComponentModel.Compiler;
using Microsoft.Crm.Sdk;
using Microsoft.Crm.Sdk.Query;
using Microsoft.Crm.SdkTypeProxy;

namespace CrmContrib.Workflow.Activities.Marketing
{
    [CrmWorkflowActivity("Add Lead to Marketing List", "CrmContrib \\ Marketing")]
    public class AddLeadToMarketingListActivity : Activity
    {
        [CrmInput("Lead")]
        [CrmReferenceTarget("lead")]
        [ValidationOption(ValidationOption.Required)]
        public Lookup Lead
        {
            get { return (Lookup)base.GetValue(AddLeadToMarketingListActivity.LeadProperty); }
            set { base.SetValue(AddLeadToMarketingListActivity.LeadProperty, value); }
        }

        public static readonly DependencyProperty LeadProperty = DependencyProperty.Register("Lead", typeof(Lookup), typeof(AddLeadToMarketingListActivity));

        [CrmInput("Marketing List")]
        [CrmReferenceTarget("list")]
        [ValidationOption(ValidationOption.Required)]
        public Lookup MarketingList
        {
            get { return (Lookup)GetValue(MarketingListProperty); }
            set { SetValue(MarketingListProperty, value); }
        }

        public static readonly DependencyProperty MarketingListProperty = DependencyProperty.Register("MarketingList", typeof(Lookup), typeof(AddLeadToMarketingListActivity));

        protected override ActivityExecutionStatus Execute(ActivityExecutionContext executionContext)
        {
            var contextService = executionContext.GetService<IContextService>();
            var workflowContext = contextService.Context;
            var crmService = workflowContext.CreateCrmService();

            var addRequest = new AddMemberListRequest();
            addRequest.EntityId = this.Lead.Value;
            addRequest.ListId = this.MarketingList.Value;

            var addResponse = (AddMemberListResponse)crmService.Execute(addRequest);

            return base.Execute(executionContext);
        }
    }
}
